#include "StdAfx.h"
#include "Util.h"
#include <iostream>
#include <fstream>
#include <shobjidl.h>
#include <sstream>

using namespace std;

wstring CUtil::ReadFileText(const wstring &filePath)
{
	wifstream textFile((wchar_t *)filePath.c_str());

	if (textFile.fail())
		return wstring(L"Can't read file");

	wstring fileText;
	wstring line;

	while (getline(textFile, line))
	{
		fileText += line;
		fileText += L"\r\n";
	}
	 
	return fileText;
}

void CUtil::WriteFileText(const wstring &filePath, const wstring& fileText)
{
	wofstream textFile((wchar_t *)filePath.c_str());
	wstringstream textStream(fileText);
	wstring line;
	while (getline(textStream, line))
	{
		textFile << line << L"\n";
	}
	textFile.close();
}

wstring CUtil::GetTempFilePath(const wstring &prefix)
{
	wchar_t sDirName[MAX_PATH];
	wchar_t sName[MAX_PATH];

    DWORD dwRetVal = GetTempPath(MAX_PATH, sDirName);
    if (dwRetVal > MAX_PATH || (dwRetVal == 0))
		throw L"GetTempPath failed";
    

    // Create a temporary file. 
    UINT uRetVal = GetTempFileName(sDirName, // directory for tmp files
								   prefix.c_str(),        // temp file name prefix 
								   0,             // create unique name 
                                   sName);    // buffer for name 
    if (uRetVal == 0)
        throw L"GetTempFileName failed";

	return wstring(sName);
}

wstring CUtil::GetOpenFileName(const wstring& title, HWND hwndOwner, bool mustExist /*=true*/)
{
	IFileDialog* pFileDialog;
	if (FAILED(CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pFileDialog))))
	{
		throw L"GetOpenFileName failed to create FileOpenDialog";
	}
	
	pFileDialog->SetTitle(title.c_str());
	FILEOPENDIALOGOPTIONS options = FOS_FORCEFILESYSTEM;
	if (mustExist)
		options |= FOS_FILEMUSTEXIST;
	pFileDialog->SetOptions(options);

	wstring fileName;
	if (SUCCEEDED(pFileDialog->Show(hwndOwner)))
	{
		IShellItem* pResult;
		if (SUCCEEDED(pFileDialog->GetResult(&pResult)))
		{
			LPWSTR pszName;
			if (SUCCEEDED(pResult->GetDisplayName(SIGDN_FILESYSPATH, &pszName)))
			{
				fileName = wstring(pszName);
				CoTaskMemFree(pszName);
			}
		}
	}
	pFileDialog->Release();
	return fileName;
}
